﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace MoneyWentWhere.DataModel.Reports
{
    class TableReportRow : IComparable
    {
        public const int ColWidth = 12;

        public readonly DateTime StartDate;
        public readonly TimeSpanUnit PeriodUnit;
        public List<PeriodAmount>[] Cells;

        public TableReportRow(DateTime startDate, TimeSpanUnit periodUnit, int columnCount)
        {
            StartDate = startDate;
            PeriodUnit = periodUnit;
            Cells = new List<PeriodAmount>[columnCount];
        }

        public void AddPeriodAmount(PeriodAmount pa, int colIndex)
        {
            if (pa.Key.StartDate != StartDate) { throw new ArgumentException("StartDate not same."); }

            if (Cells[colIndex] == null) { Cells[colIndex] = new List<PeriodAmount>(); }
            Cells[colIndex].Add(pa);
        }

        // Compare by date
        public int CompareTo(object obj)
        {
            TableReportRow that = obj as TableReportRow;
            if (that == null) { return -1; }
            return StartDate.CompareTo(that.StartDate);
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(StartDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture).PadRight(ColWidth));
            sb.Append("|");

            for (int i = 0; i < Cells.Length; i++)
            {
                decimal amount = CellAmount(i);
                if (amount == 0) { sb.Append(' ', ColWidth); }
                else
                {
                    sb.Append(amount.ToString("#,###").PadLeft(ColWidth));
                }
                sb.Append("|");
            }
            return sb.ToString();
        }

        decimal CellAmount(int colIndex)
        {
            if (Cells[colIndex] == null) { return 0; }

            decimal sum = 0;
            foreach(PeriodAmount pa in Cells[colIndex]) { sum += pa.Amount; }
            return sum;
        }
    }
}
